#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <string>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"
#include<functional>

#include<unordered_map>

const std::string defaultip = "0.0.0.0";
uint16_t defaultport = 8080;

Log lg;

enum
{
    SOCK_ERR = 1,
    BIND_ERR
};


using func_t = std::function<std::string(const std::string& ,const std::string& ip,const uint16_t& port)>;


class udpserver
{
public:
    udpserver(const uint16_t &port = defaultport, const std::string &ip = defaultip)
        : port_(port), ip_(ip), isrunning_(false), sockfd_(0)
    {
    }

    void Init()
    {
        // 创建udp套接字
        sockfd_ = socket(AF_INET, SOCK_DGRAM, 0);
        if (sockfd_ < 0)
        {
            lg(Fatal, "socket create error, sockfd:%d ", sockfd_);
            exit(SOCK_ERR);
        }
        lg(Info, "socket create success, sockfd: %d", sockfd_);

        // bind
        // 创建套接字地址结构体
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port_);
        local.sin_addr.s_addr = inet_addr(ip_.c_str());

        // bind(绑定)
        socklen_t len = sizeof(local);
        int n = bind(sockfd_, (const struct sockaddr *)&local, len);
        if (n < 0)
        {
            lg(Fatal, "bind error,errno: %d,error string: %s", errno, strerror(errno));
            exit(BIND_ERR);
        }

        // 初始化成功
        lg(Info, "bind success");
    }
    void Start(func_t func)
    {
        //服务器初始化完后，就可以进行通信了
        isrunning_ = true;
        //收消息缓冲区
        char buffer[SIZE];//1024
        while(isrunning_)
        {
            //创建客户端套接字结构体
            struct sockaddr_in client;
            bzero(&client,sizeof(client));
            socklen_t len = sizeof(client);
            //和read一样，成功就返回读取的大小
            ssize_t n = recvfrom(sockfd_,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&client,&len);
            if(n < 0)
            {
                lg(Warning, "recvfrom error, errno: %d, err string: %s", errno, strerror(errno));
                continue;
            }
            //设置消息末尾
            buffer[n] = 0;
            //构造字符串传入回调函数处理消息
            std::string info = buffer;
            //处理消息

            std::string clientip;
            uint16_t clientport;
            clientport = ntohs(client.sin_port);
            clientip = inet_ntoa(client.sin_addr);

            CheckUser(&client,clientip,clientport);


            broadcast(info,clientip,clientport);
            // std::string result = func(info,clientip,clientport);

            // //返回处理后的结果
            // sendto(sockfd_,result.c_str(),sizeof(result),0,(struct sockaddr*)&client,len);
    
        }
    }
    
    void CheckUser(struct sockaddr_in* client,const std::string& clientip,const uint16_t& clientport)
    {
        auto iter = online_user.find(clientip);
        if(iter == online_user.end())
        {
            std::cout << "[" << clientip << ":" << clientport << "]: add server!!!!!" << std::endl;
            online_user.insert({clientip,client});
        }
    }

    void broadcast(const std::string& info, const std::string& clientip, const uint16_t clientport)
    {
        std::string message = "[";
        message += clientip;
        message += ":";
        message += clientport;
        message += "]#";
        message += info;

        for(auto& [a,b] : online_user)
        {
            socklen_t len = sizeof(*b);
            sendto(sockfd_,message.c_str(),sizeof(message),0,(struct sockaddr*)b,len);
        }
    }

    ~udpserver()
    {
        if(sockfd_ > 0) close(sockfd_);
    }

private:
    int sockfd_;
    std::string ip_;
    uint16_t port_;
    bool isrunning_;
    std::unordered_map<std::string,struct sockaddr_in*> online_user;
};